package com.eastchina.fids2focs.service.handlers;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.exchange.InMessage;
import org.codehaus.xfire.handler.AbstractHandler;
import org.codehaus.xfire.transport.http.XFireServletController;
import org.jdom.Element;
import org.jdom.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.eastchina.fids2focs.common.AuthenticationManager;
import com.eastchina.fids2focs.common.GlobalConstants;
import com.eastchina.fids2focs.domain.SystemUser;


public class AuthenticationHandler extends AbstractHandler {

	// 命名空间
	public static final Namespace TOKEN_NS = Namespace.getNamespace("http://fidsii.eastchina.com");
	
	/**
	 * 权限管理对象
	 */
	@Autowired
	AuthenticationManager authMgr;
	
	String ignorePattern;
	
    /**
     * Invoke a handler.
     *  
     * @param context　The message context.
     */	
	public void invoke(MessageContext context) throws Exception {

		if (ignorePattern != null && !"".equals(ignorePattern)) {
			String[] ignores = ignorePattern.split(",");
			for (String ignore : ignores) {
				if (context.getService().getSimpleName().matches(ignore)) {
					return;
				}
			}
		}
		
		HttpServletRequest request = XFireServletController.getRequest();
        HttpSession session = request.getSession();
        // Get user information from the session
		SystemUser loginUser = (SystemUser) session.getAttribute(GlobalConstants.USER_KEY);
		if (loginUser == null) {

			// username & password
			String username = null;
			String password = null;
			String macAddr = null;
			
			// Get username and password from cookie
			request = XFireServletController.getRequest();
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if ("username".equals(cookie.getName())) {
						username = cookie.getValue();
					} else if ("password".equals(cookie.getName())) {
						password = cookie.getValue();
					} else if ("macAddr".equals(cookie.getName())) {
						macAddr = cookie.getValue();
					}
				}
			}
			
			if (username == null) {
				// Get username and password from soap header message
				InMessage message = context.getInMessage();
				if (message.getHeader() != null) {
					Element token = message.getHeader().getChild("AuthenticationToken", TOKEN_NS);
					if (token != null) {
						username = token.getChild("Username", TOKEN_NS).getValue();
				        password = token.getChild("Password", TOKEN_NS).getValue();
				        macAddr = token.getChild("MacAddr", TOKEN_NS).getValue();				        
					}
				}
			}
			
			if (username != null) {
				// Login as the specified user
				session.setAttribute(GlobalConstants.USER_KEY, authMgr.checkPermission(username, password, macAddr));			
			} else {			
				// Login as an anonymous user ?
				session.setAttribute(GlobalConstants.USER_KEY, createAnonymousUser());					
			}
		}
	}
	
	/**
	 * Create an anonymous user
	 */
	private SystemUser createAnonymousUser() {
		// FIXME
		SystemUser user = new SystemUser();
		user.setLoginId("Anonymous");
		user.setPname("Anonymous User.");
		
		return user;
	}

	public String getIgnorePattern() {
		return ignorePattern;
	}

	public void setIgnorePattern(String ignorePattern) {
		this.ignorePattern = ignorePattern;
	}
	
	
}
